import json
import pandas
import requests
from datetime import datetime
from vfeeds import DataFeed


class SinaForexFeed(DataFeed):
    httpHeaders = {
        "Referer": "https://vip.stock.finance.sina.com.cn/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0"
    }
    intervalMaps = {
        "1min": 1, "5min": 5, "15min": 15, "30min": 30, "H": 60, "D": "D", "W": "D", "M": "M"
    }

    @staticmethod
    def to_json(text):
        result = list()
        for item in text.split(";")[:-1]:
            symbol, row_data = item.strip("\n").split("=")
            row_data = row_data.strip("\"").split(",")
            row_data = {
                "title": row_data[9], "symbol": symbol[11:], "datetime": f"{row_data[10]} {row_data[0]}",
                "open": float(row_data[5]), "high": float(row_data[6]), "low": float(row_data[7]),
                "close": float(row_data[8]), "volume": float(row_data[4]), "pre_close": float(row_data[3]),
                "ask": float(row_data[1]), "bid": float(row_data[2])
            }
            result.append(row_data)
        return result

    def get_detail(self):
        results = list()
        for node in ("jbhl_forex", "jchl_forex"):
            respond = requests.get(
                url="https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getNameList",
                params={
                    "page": 1, "num": 80, "sort": "symbol", "asc": 1, "node": node, "_s_r_a": "init"
                }
            ).json()
            for item in respond:
                results.append(item["symbol"])
        return results

    def _get_min_kline(self, symbol, scale):
        url, result = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php", list()
        respond = requests.get(
            url=f"{url}/var%20_fx_saudcad_{scale}_{self.millisecond}=/NewForexService.getMinKline",
            params={
                "datalen": 2000,
                "scale": scale,
                "symbol": f"fx_s{symbol.lower()}"
            }
        )
        _, respond = respond.text.split("(")
        respond, _ = respond.split(")")
        respond = json.loads(respond)
        for item in respond:
            result.append({
                "datetime": item["d"],
                "open": float(item["o"]),
                "high": float(item["h"]),
                "low": float(item["l"]),
                "close": float(item["c"])
            })
        return pandas.DataFrame(result)

    @staticmethod
    def _get_day_kline(symbol):
        url, result = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php", list()
        code, date = symbol.lower(), datetime.now().strftime("%Y_%m_%d")
        respond = requests.get(f"{url}/var%20_fx_s{code}{date}=/NewForexService.getDayKLine", params={
            "symbol": f"fx_s{code}"
        })
        _, respond = respond.text.split("(")
        respond, _ = respond.split(")")
        respond = respond.strip("\"")
        respond = respond.split("|")
        for item in respond:
            row_data = item.strip(",").split(",")
            result.append({
                "datetime": row_data[0],
                "open": float(row_data[1]),
                "high": float(row_data[3]),
                "low": float(row_data[2]),
                "close": float(row_data[4])
            })
        return pandas.DataFrame(result)

    def get_history(self, symbol, interval, start, end, **kwargs):
        period = self.intervalMaps[interval]
        if isinstance(period, int):
            result = self._get_min_kline(symbol, period)
        else:
            result = self._get_day_kline(symbol)
        result = result.set_index(pandas.to_datetime(result["datetime"]))
        result = result.resample(interval).agg({
            "datetime": "last", "open": "first", "high": "max", "low": "min", "close": "last"
        }).dropna()
        return result.loc[start:end].to_dict(orient="records")

    def get_ticker(self, symbol):
        respond = requests.get(
            url=f"https://hq.sinajs.cn/list={symbol}",
            headers=self.httpHeaders
        )
        respond = self.to_json(respond.text)
        return respond[0]


__all__ = [SinaForexFeed]
